package com.framework.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.core.common.constant.CacheConstants;
import com.framework.system.entity.SysArea;
import com.framework.system.entity.dto.SysAreaQueryDTO;
import com.framework.system.entity.vo.SysAreaListVO;
import com.framework.system.mapper.SysAreaMapper;
import com.framework.system.service.ISysAreaService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 行政区域 服务实现类
 * </p>
 *
 * @author Kevin
 * @since 2021-08-08
 */
@Service
@AllArgsConstructor
@Slf4j
public class SysAreaServiceImpl implements ISysAreaService {

    private SysAreaMapper sysAreaMapper;

    @Override
    public Page<SysAreaListVO> selectSysAreaWithPage(Page reqPage, SysAreaQueryDTO req) {
        LambdaQueryWrapper<SysArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Objects.nonNull(req.getParentCode()), SysArea::getParentCode, req.getParentCode());
        queryWrapper.like(StrUtil.isNotBlank(req.getAreaCode()), SysArea::getAreaCode, req.getAreaCode());
        queryWrapper.like(StrUtil.isNotBlank(req.getAreaName()), SysArea::getAreaName, req.getAreaName());
        queryWrapper.orderByAsc(SysArea::getSort);
        Page<SysArea> page = sysAreaMapper.selectPage(reqPage, queryWrapper);
        Page<SysAreaListVO> voPage = BeanUtil.copyProperties(page, Page.class);
        voPage.setRecords(BeanUtil.copyToList(page.getRecords(), SysAreaListVO.class));
        return voPage;
    }

    @Cacheable(value = CacheConstants.CACHE_PREFIX_SYS_AREA, key = "#root.methodName", sync = true)
    @Override
    public List<Tree<String>> selectSysAreaWithTree() {
        List<SysArea> sysAreaList = sysAreaMapper.selectList(Wrappers.emptyWrapper());
        List treeNodeList = sysAreaList.stream().map(item -> {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(item.getAreaCode());
            treeNode.setName(item.getAreaName());
            treeNode.setParentId(item.getParentCode());
            treeNode.setWeight(item.getSort());
            return treeNode;
        }).collect(Collectors.toList());
        List<Tree<String>> treeList = TreeUtil.build(treeNodeList, "0");
        return CollectionUtils.isEmpty(treeList) ? new ArrayList() : treeList;
    }

}
